import { Suspense, lazy, useEffect, useState, useRef, useMemo } from "react";
import { BrowserRouter, Routes, Route, Link, useNavigate } from "react-router-dom";
import styles from "@/assets/scss/main.module.scss";
import axios from "axios";
import { Input, Button, Space, notification } from "antd";
import { CloseOutlined } from "@ant-design/icons";

const NotFound = lazy(() => import("./pages/route/notFound"));

function App(){
    const [treeList, setTreeList] = useState([]);
    const [menuTemp, setmenuTemp] = useState(0);
    const searchRef = useRef(null);
    const headerRef = useRef(null);
    const [searchValue, setSearchValue] = useState("");
    const scrollYRef = useRef(0);
    const loading = $.loading();

    useEffect(() => {
        initialize(`.${styles.app}`, true)
            .then(() => loadMenuData(setTreeList, loading))
            .catch(error => alert(error));
        const handleScroll = () => {
            const currentScrollY = window.scrollY;
            let scrollDirection = currentScrollY > scrollYRef.current ? "down" : "up";
            scrollYRef.current = currentScrollY;
            if(currentScrollY > 80) {
                if(scrollDirection === "down") {
                    headerRef.current.style.top = "-80px";
                } else if (scrollDirection === "up"){
                    headerRef.current.style.top = "0px";
                }
            }else{
                headerRef.current.style.top = "-180px";
            }
        };
        window.addEventListener("scroll", handleScroll);
        return () => {
            window.removeEventListener("scroll", handleScroll);
        };
    }, []);

    const routes = useMemo(() => generateRoutes(), []);

    return (
        <div className={`${styles.app} columnStartStart`}>
            <BrowserRouter>
                <AppContent 
                    treeList={treeList}
                    loading={loading}
                    menuTemp={menuTemp}
                    setmenuTemp={setmenuTemp}
                    searchRef={searchRef}
                    headerRef={headerRef}
                    searchValue={searchValue}
                    setSearchValue={setSearchValue}
                    routes={routes}
                />
            </BrowserRouter>
        </div>
    );
};

// 内部组件，用于在 BrowserRouter 内部使用 useNavigate
function AppContent({ treeList, loading, menuTemp, setmenuTemp, searchRef, headerRef, searchValue, setSearchValue, routes }) {
    const navigate = useNavigate();

    const handleSearch = () => {
        searchRef.current?.close();
        if(!searchValue) {
            notification.warning({
                message: "提示",
                description: "搜索内容不能为空",
                placement: "topRight"
            });
            return;
        };
        const type = getSearchString("type") || null;
        let Url = "/list?keyWords=" + searchValue;
        if(type) {
            Url = Url + "&type=" + type;
        };
        setSearchValue(null);
        navigate(Url);
    };

    const handleSearchIconClick = (type) => {
        if(type) {
            searchRef.current?.showModal();
        } else {
            searchRef.current?.close();
        }
    };

    return (
        <>
            <header className={styles.header} ref={headerRef}>
                <div className={`${styles.main} rowStartCenter font-18`}>
                    <img src={`${$.baseUrl}/public/imgs/icon/logo.png`} alt="" className={styles.logo} />
                    <div className="flex-1 rowEndCenter fullHeight">
                        {treeList.map((item, index) => (
                                <MenuItem key={index} item={item} index={index} menuTemp={menuTemp} setmenuTemp={setmenuTemp}/>
                        ))}
                        <div onClick={() => {handleSearchIconClick(true)}}>
                            <svg t="1759022652152" className="icon m-l-32 pointer" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4702" width="30" height="30">
                                <path d="M774.991188 759.692531l201.863039 201.863039a36.569391 36.569391 0 0 1-51.782258 51.70912L717.138411 805.257993a438.832694 438.832694 0 1 1 57.779638-45.565462zM475.561014 804.526605A365.693911 365.693911 0 1 0 475.561014 73.138782a365.693911 365.693911 0 0 0 0 731.387823z" fill="var(--text-333333)" p-id="4703"></path>
                            </svg>
                        </div>
                    </div>
                </div>
            </header>
            <main className="flex-1">
                <Routes>
                    {routes.map((route, index) => (
                        <Route key={index} path={route.path} element={route.element} />
                    ))}
                </Routes>
            </main>
            <footer className={`${styles.footer}`}>
                <div className={`${styles.main} rowAroundStart`}>
                    <div className={`${styles['footer-section']} columnStartCenter`}>
                        <h4>友情链接</h4>
                        <a href={`${window.location.protocol}//${window.location.hostname}:5320`} target="_blank">网站</a>
                        <a href={`${window.location.protocol}//${window.location.hostname}:5322`} target="_blank">管理后台</a>
                    </div>
                    <div className={`${styles['footer-section']} columnStartCenter`}>
                        <h4>快捷链接平台</h4>
                        <a href={`${window.location.protocol}//${window.location.hostname}:5321/404`} target="_blank">使用清单</a>
                        <a href={`${window.location.protocol}//${window.location.hostname}:5321/404`} target="_blank">前端面试常见题</a>
                        <a href={`${window.location.protocol}//${window.location.hostname}:5320/pages/loading/index.html`} target="_blank">加载Loading</a>
                    </div>
                    <div className={`${styles['footer-section']} columnCenterCenter`} style={{height: "100%"}}>
                        <img src={`${$.baseUrl}/public/imgs/icon/logo.png`} alt="" className={styles.FooterLogo} />
                    </div>
                </div>
                <div className={styles['footer-bottom']}>
                    <p>© 2020-{new Date().getFullYear()} 我的技术博客 | 记录、分享、成长</p>
                    <p>Powered by React & Node.js</p>
                </div>
            </footer>
            <dialog className={styles.dialog} ref={searchRef}>
                <div className="fullScreen rowCenterCenter rela">
                    <div className={`${styles.dialogClose} pointer`} onClick={() => {handleSearchIconClick(false)}}>
                        <CloseOutlined />
                    </div>
                    <Space.Compact style={{ width: '450px' }}>
                        <Input 
                            placeholder="请输入关键词搜索" 
                            className={`${styles.searchInput} font-20`} 
                            value={searchValue} 
                            onChange={(e) => setSearchValue(e.target.value)}
                            onPressEnter={handleSearch}
                        />
                        <Button type="primary" size="large" onClick={handleSearch}>
                            搜索
                        </Button>
                    </Space.Compact>
                </div>
            </dialog>
        </>
    );
}

// 动态识别 src/pages 下的所有页面，并生成路由
function generateRoutes (){
    const pages = import.meta.glob("./pages/view/**/*.jsx", { eager: false });
    const routes = [];
    for (const path in pages) {
        const componentImporter = pages[path];
        let routerPath = path
            .replace("./pages/view/", "/")
            .replace(/\.jsx$/, "")
            .replace(/\/Index$/, "")
            .replace(/^\/index$/, "/")
            .replace(/\[(\w+)\]\.jsx$/, '/:$1');
        if (routerPath === "") routerPath = "/";
        
        const LazyComponent = lazy(componentImporter);
        routes.push({
            path: routerPath,
            element: (
                <Suspense fallback={<div>Loading...</div>}>
                    <LazyComponent />
                </Suspense>
            )
        });
    };
    routes.push({
        path: "*",
        element: (
            <Suspense fallback={<div>Loading...</div>}>
                <NotFound />
            </Suspense>
        )
    });
    return routes;
};

// 查找节点函数
function findNode(treeList, parentID){
    for (let i = 0; i < treeList.length; i++) {
        let node = treeList[i];
        if (node.id === parentID) return node;
        else {
            if (node.children && node.children.length > 0) {
                let oRet = findNode(node.children, parentID);
                if (oRet !== null) {
                    return oRet;
                }
            }
        }
    }
    return null;
};

// 加载菜单数据
async function loadMenuData(setTreeList,loading) {
    loading.show();
    try {
        const response = await axios.get(`${$.baseUrl}/api/json/data`);
        if (response.data.success) {
            const newTreeList = [];
            for (let i = 0; i < response.data.data.menu.length; i++) {
                if (Number(response.data.data.menu[i].type) === 3) {
                    response.data.data.menu[i].data.forEach(item => {
                        let parent = findNode(newTreeList, item.uid);
                        if (parent !== null) {
                            if (!parent.children) parent.children = [];
                            parent.children.push(item);
                        } else {
                            newTreeList.push(item);
                        }
                    });
                }
            }
            setTreeList(newTreeList);
        }
    } catch (error) {
        alert(error.message);
    } finally {
        loading.hide();
    }
};

// 菜单组件
function MenuItem({ item, index, menuTemp, setmenuTemp }) {
    // 修改判断逻辑：检查是否是端口路径（格式如 ":5320"）
    const isPortPath = /^:\d+$/.test(item.path);
    
    const buildFullUrl = (path) => {
        // 简化逻辑，直接提取端口号
        const port = path.replace(':', '');
        return `${window.location.protocol}//${window.location.hostname}:${port}`;
    };

    const handleClick = (e) => {
        if (item.path === "about:black") {
            e.preventDefault();
            e.stopPropagation();
            return;
        }
        setmenuTemp(index);
    };

    const renderLink = () => {
        if (item.path === "about:black") {
            return (
                <div 
                    className={`${styles.link} pointer`} 
                    onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                    }}
                >
                    <div className={`${styles.oneMenu}`}>
                        <div className="rowCenterCenter">{item.zh}</div>
                        <div className="rowCenterCenter">{item.en}</div>
                    </div>
                </div>
            );
        } else if (isPortPath) {
            return (
                <a 
                    href={buildFullUrl(item.path)} 
                    className={styles.link} 
                    target="_blank" 
                    rel="noopener noreferrer"
                    onClick={(e) => {
                        // 确保点击事件正常处理
                        e.stopPropagation();
                        setmenuTemp(index);
                    }}
                >
                    <div className={`${styles.oneMenu}`}>
                        <div className="rowCenterCenter">{item.zh}</div>
                        <div className="rowCenterCenter">{item.en}</div>
                    </div>
                </a>
            );
        } else {
            return (
                <Link to={item.path} className={styles.link}>
                    <div className={`${styles.oneMenu}`}>
                        <div className="rowCenterCenter">{item.zh}</div>
                        <div className="rowCenterCenter">{item.en}</div>
                    </div>
                </Link>
            );
        }
    };

    return (
        <div 
            key={index} 
            className={`${styles.item} ${index === menuTemp ? styles.select : ''} rowStartCenter rela`} 
            onClick={handleClick}
        >
            {renderLink()}
            {/* 子菜单部分保持不变 */}
            {item.children && item.children.length > 0 && (
                <div className={styles['item-ItemBox']}>
                    <div className={styles["item-itemBox-box"]}>
                        {item.children.map((child, childIndex) => {
                            const isChildPortPath = /^:\d+$/.test(child.path);
                            
                            return (
                                <div 
                                    key={childIndex} 
                                    className={styles['item-item']}
                                    onClick={(e) => {
                                        if (child.path === "about:black") {
                                            e.preventDefault();
                                            e.stopPropagation();
                                            return;
                                        }
                                        setmenuTemp(index);
                                    }}
                                >
                                    {child.path === "about:black" ? (
                                        <div 
                                            className={`${styles.oneMenu2} font-16 pointer`}
                                            onClick={(e) => {
                                                e.preventDefault();
                                                e.stopPropagation();
                                            }}
                                        >
                                            <div className="rowCenterCenter">{child.zh}</div>
                                            <div className="rowCenterCenter">{child.en}</div>
                                        </div>
                                    ) : isChildPortPath ? (
                                        <a 
                                            href={buildFullUrl(child.path)} 
                                            className={styles.link} 
                                            target="_blank" 
                                            rel="noopener noreferrer"
                                            onClick={(e) => e.stopPropagation()}
                                        >
                                            <div className={`${styles.oneMenu2} font-16`}>
                                                <div className="rowCenterCenter">{child.zh}</div>
                                                <div className="rowCenterCenter">{child.en}</div>
                                            </div>
                                        </a>
                                    ) : (
                                        <Link to={child.path} className={styles.link}>
                                            <div className={`${styles.oneMenu2} font-16`}>
                                                <div className="rowCenterCenter">{child.zh}</div>
                                                <div className="rowCenterCenter">{child.en}</div>
                                            </div>
                                        </Link>
                                    )}
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}
        </div>
    );
}

export default App;